package com.ttl.bc.ic.item;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;



import com.ttl.bc.ap.debitnote2.db.BCDebitNote2DAO;
import com.ttl.bc.ic.stktransfer2.BCStkTransfer2;
import com.ttl.bc.ic.stktransfer2.BCStkTransfer2DAO;
import com.ttl.bc.master.itemunit.BCItemUnitBean;
import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;
import com.ttl.common.util.PageJsp;
import com.ttl.ittl.pack.ITTL_Pack;
import com.ttl.ittl.view.ViewITTL_Pack;

public class BCItemBO {

	@SuppressWarnings({ "rawtypes" })
	public void setPage(HttpServletRequest request, String hql) {

		int pageNumber = 1, maxEntriesPerPage=50, lineNumber=1;		
		try {			
			pageNumber = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {}
		
		if(request.getParameter("maxEntriesPerPage")!=null) {
			maxEntriesPerPage = Integer.parseInt(request.getParameter("maxEntriesPerPage"));			
		}
		if(request.getParameter("lineNumber")!=null) {
			request.setAttribute("lineNumber", request.getParameter("lineNumber"));
		}else {
			request.setAttribute("lineNumber", lineNumber);
		}
				
//		Page page = CommonUtils.getHibernatePage(hql, pageNumber, maxEntriesPerPage);				
		Page page = CommonUtils.getHibernateScrollableResultsPage(hql, pageNumber, maxEntriesPerPage);		
		
		request.setAttribute("maxEntriesPerPage", maxEntriesPerPage);
		request.setAttribute("allElement", page.getAllElement());
		
		
//start
		if(page.getResultList()!=null && page.getResultList().size()>0) {
			String hql2 = "select itemCode, sum(qty) from BCStkIssueSub2Query " +
					"WHERE (ittl_status=0 or ittl_status is null) and itemCode in ('"; 
			for (int i = 0; i < page.getResultList().size(); i++) {
				View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
				hql2 += item.getItemCode()+"','";
			}
			hql2 += "') ";
			hql2 +=	"group by itemCode " +
					"order by itemCode ";
			//System.out.println(hql2);
			List list = CommonUtils.getSumQty(hql2,maxEntriesPerPage);
			//System.out.println(list.size());
			
			Iterator it = list.iterator();
			while (it.hasNext()) {
				Object[] tuple = (Object[]) it.next();
				for (int i = 0; i < page.getResultList().size(); i++) {
					
//					BCItemBean item = (BCItemBean)page.getResultList().get(i);
					View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
					
					
					if(tuple[0].toString().equalsIgnoreCase(item.getItemCode())) {
						
						item.setQtyReserve(Double.valueOf(""+tuple[1]) );
						 
					}
				}
			}	
			
//			ArrayList unitCodeList = (ArrayList)request.getSession().getAttribute("unitCodeList");
//			
//			for (int i = 0; i < page.getResultList().size(); i++) {
//				BCItemBean item = (BCItemBean)page.getResultList().get(i);
//				
//				for (int j = 0; j < unitCodeList.size(); j++) {
//					BCItemUnitBean unit = (BCItemUnitBean)unitCodeList.get(j);
//					
//					if(unit.getCode().equalsIgnoreCase(item.getDefStkUnitCode())) {
//						item.setMyDescription(unit.getName());
//					}				
//				}			
//			}
		}
//end
		
		if(page.getAllElement()>0) {
			
			request.setAttribute("itemResults", page.getResultList() );
			request.setAttribute("offset", (pageNumber-1)*maxEntriesPerPage);
			request.setAttribute("currentPage", page.getCurrentPage());
			
			if(page.isNextPage()==true) {
				request.setAttribute("nextPage", page.getCurrentPage()+1);
			}
			
			if(page.isPreviousPage()==true) {
				request.setAttribute("previousPage", page.getCurrentPage()-1);
			}
			
			if(page.isFirstPage()==true) {
				request.setAttribute("firstPage", 1);
			}		
			
			if(page.isLastPage()==true && page.getMaxEntriesPerPage()!=0) {
				if(page.getAllElement()%page.getMaxEntriesPerPage()==0) {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage());	
				}else {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage()+1);
				}						
			}
		}	
	}

	public boolean pack(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)  {
		
		try {
			String user 	 = (String)request.getSession().getAttribute("userName");
			System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCItemAction #mode :pack");		
							
			DynaActionForm f = (DynaActionForm) form;		
			String itemFind= CommonUtils.getConvertStringToUTF8(f.get("itemFind").toString());
															
			String hql = getHqlPack(itemFind); 
			System.out.println(hql);
			int pageNumber = CommonUtils.getPageNumber(request);
			int maxEntriesPerPage=CommonUtils.getMaxEntriesPerPage(request);
			
			PageJsp p = CommonUtils.getScrollableResultsPage(hql,pageNumber,maxEntriesPerPage);
			CommonUtils.setAttributeJsp(request, p);
			
			request.setAttribute("itemFind", itemFind);	
			
			return true;
		}catch (Exception e) {
			System.out.println(e.getStackTrace());
			return false;	
		}
	}

	private String getHqlPack(String itemFind) {
		return "FROM ViewITTL_Pack WHERE (itemCode like '%"+itemFind+"%' or itemName like '%"+itemFind+"%' or barcode like '%"+itemFind+"%' or barcodeName like '%"+itemFind+"%' ) " +
			   " and (itemCode like '2-%' or itemCode like '3-%')" +
			   " ORDER BY itemCode";
	}

	public boolean viewpack(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
		
			DynaActionForm f = (DynaActionForm) form;		
			String itemFind= CommonUtils.getConvertStringToUTF8(f.get("itemFind").toString());															
			String hql = getHqlPack(itemFind); 			
			ArrayList<ViewITTL_Pack> al = (ArrayList<ViewITTL_Pack>)new BCStkTransfer2DAO().find(hql);
			if (al.size()>0) {
				//ViewITTL_Pack v = (ViewITTL_Pack)al.get(0);
				request.setAttribute("v", al.get(0));
			}
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean updatepack(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		ViewITTL_Pack v = setBean(request);
		
		request.setAttribute("message", "แก้ไขข้อมูลเรียบร้อย");
		request.setAttribute("pageForward", "<meta http-equiv='refresh' content='5;" +
				"url=stock.do?mode=pack&itemFind="+v.getItemCode()+"'> ");	

		return 	new BCItemDAO().updatepack(v);
	}

	private ViewITTL_Pack setBean(HttpServletRequest request) {
		String packSize = request.getParameter("packSize");
		if(packSize==null || packSize.trim().length()==0)
			packSize = "0";		

		String stockMin = request.getParameter("stockMin");
		if(stockMin==null || stockMin.trim().length()==0)
			stockMin = "0";

		String stockMax = request.getParameter("stockMax");
		if(stockMax==null || stockMax.trim().length()==0)
			stockMax = "0";		
		
		
		ViewITTL_Pack v = new ViewITTL_Pack();
		v.setItemCode(request.getParameter("itemCode"));

			
		v.setPackSize(Float.valueOf(packSize));
		v.setStockMin(Float.valueOf(stockMin));
		v.setStockMax(Float.valueOf(stockMax));
		
		v.setBarcode(request.getParameter("barcode"));
		v.setBarcodeName(request.getParameter("barcodeName"));
		return v;
	}
	
	public void setPage2(HttpServletRequest request, String hql) {
		int pageNumber = 1, maxEntriesPerPage=50, lineNumber=1;		
		try {			
			pageNumber = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {}
		
		if(request.getParameter("maxEntriesPerPage")!=null) {
			maxEntriesPerPage = Integer.parseInt(request.getParameter("maxEntriesPerPage"));			
		}
		if(request.getParameter("lineNumber")!=null) {
			request.setAttribute("lineNumber", request.getParameter("lineNumber"));
		}else {
			request.setAttribute("lineNumber", lineNumber);
		}
				
//		Page page = CommonUtils.getHibernatePage(hql, pageNumber, maxEntriesPerPage);				
		Page page = CommonUtils.getHibernateScrollableResultsPage(hql, pageNumber, maxEntriesPerPage);		
		
		request.setAttribute("maxEntriesPerPage", maxEntriesPerPage);
		request.setAttribute("allElement", page.getAllElement());
		
		
//start
		if(page.getResultList()!=null && page.getResultList().size()>0) {
			String hql2 = "select itemCode, sum(qty) from BCStkIssueSub2Query " +
					"WHERE (ittl_status=0 or ittl_status is null) and itemCode in ('"; 
			for (int i = 0; i < page.getResultList().size(); i++) {
				//old BCItemBean item = (BCItemBean)page.getResultList().get(i);
				View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
				hql2 += item.getItemCode()+"','";
			}
			hql2 += "') ";
			hql2 +=	"group by itemCode " +
					"order by itemCode ";
			//System.out.println(hql2);
			List list = CommonUtils.getSumQty(hql2,maxEntriesPerPage);
			//System.out.println(list.size());
			
			Iterator it = list.iterator();
			while (it.hasNext()) {
				Object[] tuple = (Object[]) it.next();
				for (int i = 0; i < page.getResultList().size(); i++) {
					
					//oldBCItemBean item = (BCItemBean)page.getResultList().get(i);
					View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
					
					
					if(tuple[0].toString().equalsIgnoreCase(item.getItemCode())) {
						
						item.setQtyReserve(Double.valueOf(""+tuple[1]) );
						 
					}
				}
			}	
		}
//end
		
		if(page.getAllElement()>0) {
			
			request.setAttribute("itemResults", page.getResultList() );
			request.setAttribute("offset", (pageNumber-1)*maxEntriesPerPage);
			request.setAttribute("currentPage", page.getCurrentPage());
			
			if(page.isNextPage()==true) {
				request.setAttribute("nextPage", page.getCurrentPage()+1);
			}
			
			if(page.isPreviousPage()==true) {
				request.setAttribute("previousPage", page.getCurrentPage()-1);
			}
			
			if(page.isFirstPage()==true) {
				request.setAttribute("firstPage", 1);
			}		
			
			if(page.isLastPage()==true && page.getMaxEntriesPerPage()!=0) {
				if(page.getAllElement()%page.getMaxEntriesPerPage()==0) {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage());	
				}else {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage()+1);
				}						
			}
		}			
	}

	public void setPage3(HttpServletRequest request, String hql) {
		int pageNumber = 1, maxEntriesPerPage=50, lineNumber=1;		
		try {			
			pageNumber = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {}
		
		if(request.getParameter("maxEntriesPerPage")!=null) {
			maxEntriesPerPage = Integer.parseInt(request.getParameter("maxEntriesPerPage"));			
		}
		if(request.getParameter("lineNumber")!=null) {
			request.setAttribute("lineNumber", request.getParameter("lineNumber"));
		}else {
			request.setAttribute("lineNumber", lineNumber);
		}
				
//		Page page = CommonUtils.getHibernatePage(hql, pageNumber, maxEntriesPerPage);				
		Page page = CommonUtils.getHibernateScrollableResultsPage(hql, pageNumber, maxEntriesPerPage);		
		
		request.setAttribute("maxEntriesPerPage", maxEntriesPerPage);
		request.setAttribute("allElement", page.getAllElement());
		
		
//start
		if(page.getResultList()!=null && page.getResultList().size()>0) {
			String hql2 = "select itemCode, sum(qty) from BCStkIssueSub2Query " +
					"WHERE (ittl_status=0 or ittl_status is null) and itemCode in ('"; 
			for (int i = 0; i < page.getResultList().size(); i++) {
				View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
				hql2 += item.getItemCode()+"','";
			}
			hql2 += "') ";
			hql2 +=	"group by itemCode " +
					"order by itemCode ";
			//System.out.println(hql2);
			List list = CommonUtils.getSumQty(hql2,maxEntriesPerPage);
			//System.out.println(list.size());
			
			Iterator it = list.iterator();
			while (it.hasNext()) {
				Object[] tuple = (Object[]) it.next();
				for (int i = 0; i < page.getResultList().size(); i++) {
					
//					BCItemBean item = (BCItemBean)page.getResultList().get(i);
					View_BCStkLocation item = (View_BCStkLocation)page.getResultList().get(i);
					
					
					if(tuple[0].toString().equalsIgnoreCase(item.getItemCode())) {
						
						item.setQtyReserve(Double.valueOf(""+tuple[1]) );
						 
					}
				}
			}	
		}
//end
		
		if(page.getAllElement()>0) {
			
			request.setAttribute("itemResults", page.getResultList() );
			request.setAttribute("offset", (pageNumber-1)*maxEntriesPerPage);
			request.setAttribute("currentPage", page.getCurrentPage());
			
			if(page.isNextPage()==true) {
				request.setAttribute("nextPage", page.getCurrentPage()+1);
			}
			
			if(page.isPreviousPage()==true) {
				request.setAttribute("previousPage", page.getCurrentPage()-1);
			}
			
			if(page.isFirstPage()==true) {
				request.setAttribute("firstPage", 1);
			}		
			
			if(page.isLastPage()==true && page.getMaxEntriesPerPage()!=0) {
				if(page.getAllElement()%page.getMaxEntriesPerPage()==0) {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage());	
				}else {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage()+1);
				}						
			}
		}			
	}
}
